﻿using System;
using System.Data;
using Loki.Data;
using Luna.Data.Common;

namespace Luna.Data
{
    public abstract class LunaEntityMapper<TDataEntity, TDataInterface> : LunaMapper<TDataEntity, TDataInterface>
        where TDataInterface : IDataEntity<Guid>, IReferenceData
        where TDataEntity : TDataInterface
    {
        protected LunaEntityMapper()
            : base()
        {
        }

        public ReferenceDataMapper<TDataEntity> ReferenceMapper { get; set; }

        public override void Delete(IDbTransaction transaction, Guid entityKey)
        {
            base.Delete(transaction, entityKey);
            ReferenceMapper.Delete(transaction, entityKey);
        }

        public override void Save(IDbTransaction transaction, TDataInterface entity)
        {
            bool persisted = entity.AlreadyPersisted;
            ReferenceMapper.Save(transaction, entity);

            entity.AlreadyPersisted = persisted;
            base.Save(transaction, entity);
        }

        protected override void LoadSubObjects(TDataInterface entity, IDataRecord record)
        {
            ReferenceMapper.LoadFromDataRecord(entity, record);
        }
    }
}